package com.eightbears.beboy.ui.user.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.SystemMessageAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.SystemMessageEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_PAGE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SYSTEM_MESSAGE;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.entity.SystemMessageEntity.MESSAGE_TYPE_COMMON;
import static com.eightbears.beboy.entity.SystemMessageEntity.MESSAGE_TYPE_RED;
import static com.eightbears.beboy.entity.SystemMessageEntity.MESSAGE_TYPE_VIP;

public class SystemMessageActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    public static final String PARAMS_IS_SYSTEM_MESSAGE = "systemRed";


    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;

    private SystemMessageAdapter systemMessageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stystem_message);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(getIntent().getExtras().getString("userId"));
        //指定会话消息未读数清零
        conversation.markAllMessagesAsRead();
        initAdapter();
        tv_title.setText("系统");
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initEvent() {
        systemMessageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                SystemMessageEntity.SystemMessage systemMessageEntity
                        = (SystemMessageEntity.SystemMessage) adapter.getData().get(position);
                switch (view.getId()){
                    case R.id.ll_item:
                        switch (systemMessageEntity.getType()){
                            case MESSAGE_TYPE_COMMON:

                                break;
                            case MESSAGE_TYPE_RED:
                                startLocalActivity(SystemMessageActivity.this, RedActivity.class, PARAMS_IS_SYSTEM_MESSAGE, true);
                                break;
                            case MESSAGE_TYPE_VIP:

                                break;
                        }
                        break;
                }

            }
        });

        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back) void back(){
        finish();
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setProgressViewOffset(true, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        systemMessageAdapter = new SystemMessageAdapter();
        systemMessageAdapter.openLoadAnimation();
        systemMessageAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(systemMessageAdapter);

    }

    private void getData() {
        swipeLayout.setRefreshing(true);
        OkHttpUtils.get().url(URL_SYSTEM_MESSAGE)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams(PARAM_URL_SIZE, PARAMS_PAGE_SIZE+"")
                .addParams(PARAM_URL_PAGE, page + "")
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                SystemMessageEntity systemMessageEntity = GsonUtil.fromJson(response, SystemMessageEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(systemMessageEntity.getStatus_code())) {
                    isEnd = systemMessageEntity.getData().getIs_end();
                    if (page == 1)
                        systemMessageAdapter.setNewData(systemMessageEntity.getData().getList());
                    else {
                        systemMessageAdapter.addData(systemMessageEntity.getData().getList());
                        systemMessageAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SystemMessageActivity.this, status_error);
            }
        });
    }


    @Override
    public void onRefresh() {
        systemMessageAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                systemMessageAdapter.getData().clear();
                getData();
                systemMessageAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    systemMessageAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(SystemMessageActivity.this, R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        systemMessageAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }
}
